<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue';
import { useAntdForm, useFormRules } from '@/hooks/common/form';
import { hostCreateApi, hostEditApi } from '@/service/api/businessApi';
import { useProjectStore } from '@/store/modules/project';
import { getewayHooks } from '@/views/breedingManage/getewayManage/getewayHooks';
const projectStore = useProjectStore();
defineOptions({
  name: 'TerminalOperateDrawer'
});

interface Props {
  operateType: AntDesign.TableOperateType;
  rowData?: any | null;
}

// 获取网关数据
const { getGetewayList } = getewayHooks();
const getewayData: any = ref([]);

onMounted(async () => {
  getewayData.value = await getGetewayList();
});

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, resetFields } = useAntdForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<AntDesign.TableOperateType, string> = {
    add: '新增终端',
    edit: '编辑终端'
  };
  return titles[props.operateType];
});

const model: any = reactive(createDefaultModel());

function createDefaultModel(): any {
  return {};
}

const rules: any = {
  collectionNo: defaultRequiredRule,
  hostNo: defaultRequiredRule,
  hostName: defaultRequiredRule,
};

/** the enabled role options */
async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    await nextTick();
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

const doAddSubmit = async () => {
  const res = await hostCreateApi({
    ...model,
    projectId: projectStore.currentProject?.id
  });
  if (res.error === null) {
    window.$message?.success('新增成功');
    closeDrawer();
    emit('submitted');
  }
};
const doEditSubmit = async () => {
    console.log(model)
  const res = await hostEditApi({
    ...model
  });
  if (res.error === null) {
    window.$message?.success('更新成功');
    closeDrawer();
    emit('submitted');
  }
};

async function handleSubmit() {
  await validate();
  if (props.operateType === 'add') {
    await doAddSubmit();
  }
  if (props.operateType === 'edit') {
    await doEditSubmit();
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    resetFields();
  }
});
</script>

<template>
  <AModal v-model:open="visible" :title="title" :width="560" :maskClosable="false">
    <AForm ref="formRef" layout="vertical" :model="model" :rules="rules">
      <AFormItem label="终端编码" name="hostNo">
        <AInput v-model:value="model.hostNo" placeholder="请输入终端编码" />
      </AFormItem>
      <AFormItem label="终端名称" name="hostName">
        <AInput v-model:value="model.hostName" placeholder="请输入终端名称" />
      </AFormItem>
      <AFormItem label="网关编码" name="collectionNo" class="m-0">
        <ASelect
          v-model:value="model.collectionNo"
          placeholder="请选择网关编码"
          @change="(val, option: any) => (model.collectionId = option.id)"
        >
          <ASelectOption v-for="item in getewayData" :id="item.id" :key="item.collectionNo" :value="item.collectionNo">
            {{ item.collectionNo }}
          </ASelectOption>
        </ASelect>
      </AFormItem>
      <AFormItem label="备注" name="remark">
        <ATextarea v-model:value="model.remark" placeholder="请输入备注" />
      </AFormItem>
    </AForm>
    <template #footer>
      <ASpace :size="16">
        <AButton @click="closeDrawer">取消</AButton>
        <AButton type="primary" @click="handleSubmit">确认</AButton>
      </ASpace>
    </template>
  </AModal>
</template>

<style scoped></style>
